package com.shwread.android.ui.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.OrderDetailActivity;
import com.shwread.android.qysw.activity.OrderPayActivity;
import com.shwread.android.qysw10000204.R;
import com.shwread.android.ui.customview.MyListView;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.Logger;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

import logic.bean.OrderDetailColum;
import logic.bean.OrderDetailInfo;
import logic.constants.DefaultConsts;
import logic.util.IRefreshViewListener;
import logic.util.MoneyUtil;
import logic.util.NetworkUtil;
import logic.util.PicassoUtil;
import logic.util.Utils;


/**
 * 代付款页面
 *
 * @author zhangnannan
 */
public class MyGoodsNoPayView
        extends
        LinearLayout
        implements
        IRefreshViewListener {

    private Context mContext;
    private MyListView mContentListView;
    private List<OrderDetailColum> goodsList = new ArrayList<OrderDetailColum>(); //单个订单商品详情
    private List<OrderDetailInfo> orderList = new ArrayList<OrderDetailInfo>(); //所有订单信息

    private ContentAdapter mContentAdapter;
    private SubOrderAdapter subOrderAdapter;
    private PullToRefreshScrollView psView;

    private int flag = 0;
    private int pagelength = 5;                                //默认一页显示多少条数据
    private long lastOrderCreatTime = 0L;                               //当前页最后一条订单的创建时间
    private int currentPageLength = 1;                                //此次接口请求回来的数据长度
    private LoadingView loadingView;

    private ImageView ivEmptyIcon;
    private TextView tvEmptyConetxt;
    private TextView tvEmptyButon;
    private boolean isRefresh = true;

    public MyGoodsNoPayView(Context context) {
        super(context);
        mContext = context;
        initWithContext(context);
    }

    @SuppressLint("NewApi")
    public MyGoodsNoPayView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initWithContext(context);
    }

    public MyGoodsNoPayView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initWithContext(context);
    }

    private void initWithContext(Context context) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        LinearLayout containerView = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.my_goods_list_lay, null);
        psView = (PullToRefreshScrollView) containerView.findViewById(R.id.my_goods_psview);

        View mListView = (View) LayoutInflater.from(context).inflate(R.layout.my_goods_list, null);
        mContentListView = (MyListView) mListView.findViewById(R.id.my_goods_listview);

        //		subOrderAdapter = new SubOrderAdapter();
        mContentAdapter = new ContentAdapter();
        mContentListView.setAdapter(mContentAdapter);
        psView.addView(mListView);

        //为空时的视图
        View Vempety = LayoutInflater.from(context).inflate(R.layout.my_goods_empty_lay, null);
        ivEmptyIcon = (ImageView) Vempety.findViewById(R.id.my_goods_empty_lay_empey_icon_iv);
        tvEmptyConetxt = (TextView) Vempety.findViewById(R.id.my_goods_empty_lay_conetxt_tv);
        tvEmptyButon = (TextView) Vempety.findViewById(R.id.my_goods_empty_lay_button_tv);
        tvEmptyConetxt.setText("您还没有代付款的订单");
        tvEmptyButon.setVisibility(View.GONE);

        loadingView = (LoadingView) containerView.findViewById(R.id.my_goods_loading_view);
        loadingView.setLoadingAnim(R.drawable.home_progress);
        loadingView.setEmptyView(Vempety);
        changeLoadingStatus(0);

        addView(containerView, lp);

        getData(0);

        PullToRefreshUtil.initLabel(mContext, psView);
        psView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                if (psView.isHeaderShown()) { //下拉刷新
                    refresh();
                } else if (psView.isFooterShown()) { //上拉加载
                    loadMore();
                }
            }

        });

    }

    /**
     * 上拉加载更多
     */
    private void loadMore() {
        //				Utils.showToast(mContext, "上拉加载更多");
        if (orderList.size() > 0) {
            lastOrderCreatTime = orderList.get(orderList.size() - 1).getCreateTime();
        } else {
            lastOrderCreatTime = 0L;
        }
        if (currentPageLength < pagelength) {
            PullToRefreshUtil.setLoadLabel(psView, "没有更多数据了");
            psView.onRefreshComplete();
        } else {

            getData(2);
        }
    }

    /**
     * 下拉刷新
     */
    private void refresh() {
        //				Utils.showToast(mContext, "下拉刷新");
        lastOrderCreatTime = 0L;
        getData(1);
    }

    private void changeLoadingStatus(int status) {
        psView.setVisibility(status == 2 ? View.VISIBLE : View.GONE);
        loadingView.setVisibility(status == 2 ? View.GONE : View.VISIBLE);
        if (status != 2) loadingView.changeLoadingStatus(status);
    }
    /**
     * 关闭加载动画
     * int flag,int statue
     * flag 0首次加载，1为下拉刷新，2为上拉加载更多
     * status 0:加载中，1：加载空白，2 为加载成功 -1：加载失败
     */
//	private void stopLoading(int flag, int status) {
//		if (flag == 0)
//		{
//			loadingView.changeLoadingStatus(status);
//		}
//		else
//		{
//			psView.onRefreshComplete();
//		}
//	}

    /**
     * 获取数据
     */
    private void getData(int a) {
        this.flag = a;
        if (NetworkUtil.isNetAvailable(mContext)) {
            NewActionHelp.qryUserOrders(mContext, pagelength, lastOrderCreatTime, "0", new getDataListener());
        } else {
            new NoNetDialog(mContext);
        }
        isRefresh = false;
    }

    private class getDataListener
            extends
            ObjectHttpResponseHandler<List<OrderDetailInfo>> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Logger.e("错误状态妈--------" + Integer.toString(statusCode));
            Logger.e(throwable);
            currentPageLength = 4;
            if (statusCode < 1000) {

                Utils.ToastShow(mContext, "网络错误");
            } else {
                Utils.ToastShow(mContext, "请求出错");
            }
//			stopLoading(flag, -1);
            changeLoadingStatus(-1);
            isRefresh = true;
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, List<OrderDetailInfo> object, String responseString) {
            System.out.println("xxxxxxxxxxxxxxxxxxx_" + responseString);
            Logger.i(responseString);
            if (object.size() > 0) {
                currentPageLength = object.size();
                //关闭加载动画
//				stopLoading(flag, 2);
                //清空list
                if (flag != 2) {
                    if (orderList.size() > 0) orderList.clear();
                    orderList.addAll(object);
                } else {
                    orderList.addAll(object);
                }

                mContentAdapter.notifyDataSetChanged();
                changeLoadingStatus(2);
                psView.onRefreshComplete();
            } else {
                if (flag != 2) {
                    orderList.clear();
                }
                if (orderList != null && orderList.size() > 0) {
                    changeLoadingStatus(2);
                    psView.onRefreshComplete();
                } else {
                    currentPageLength = 0;
                    changeLoadingStatus(1);
                }
            }
            isRefresh = true;
        }

        @Override
        public Type getType() {
            return new TypeToken<List<OrderDetailInfo>>() {
            }.getType();
        }

    }

    /****************
     * 全部订单的 Adapter
     ***********************/

    private class ContentAdapter
            extends
            BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return orderList.size() <= 0 ? 0 : orderList.size();
        }

        @Override
        public Object getItem(int position) {
            return (orderList == null || orderList.size() == 0) ? null : orderList.get(position);
        }

        @Override
        public long getItemId(int position) {

            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.my_goods_list_item, null);
                viewHolder.tvOrderNumber = (TextView) convertView.findViewById(R.id.goods_detail_item_top_order_number);
                viewHolder.tvOrderState = (TextView) convertView.findViewById(R.id.goods_detail_item_top_order_state);
                viewHolder.lvOrderView = (MyListView) convertView.findViewById(R.id.my_goods_list_item_listview);
                viewHolder.tvGoodsTotalPrice = (TextView) convertView.findViewById(R.id.goods_detail_item_bottom_total_pay_tv);
                viewHolder.butGoodsClose = (Button) convertView.findViewById(R.id.goods_detail_item_bottom_close_btn);
                viewHolder.butGoodsComment = (Button) convertView.findViewById(R.id.goods_detail_item_bottom_comment_btn);
                viewHolder.butGoodsDeliver = (Button) convertView.findViewById(R.id.goods_detail_item_bottom_deliver_btn);
                viewHolder.butGoodsPay = (Button) convertView.findViewById(R.id.goods_detail_item_bottom_pay_btn);
                viewHolder.butGoodsComment.setVisibility(View.GONE);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            final OrderDetailInfo orderDetailInfo = (OrderDetailInfo) getItem(position);
            viewHolder.tvOrderNumber.setText("订单号:" + orderDetailInfo.getOrderSerial());
            viewHolder.tvOrderNumber.setVisibility(View.VISIBLE);
//			viewHolder.tvGoodsTotalPrice.setText(" ¥" + String.valueOf(MoneyUtil.divide(orderDetailInfo.getTotalMoney(), 100)));
            viewHolder.tvGoodsTotalPrice.setText(" ¥" + Utils.getMoneyFormat(MoneyUtil.divide(orderDetailInfo.getActualMoney(), 100)));
            //设置状态
            viewHolder.tvOrderState.setVisibility(View.VISIBLE);

            viewHolder.tvOrderState.setText("待付款");
            viewHolder.butGoodsClose.setVisibility(View.GONE);
            viewHolder.butGoodsPay.setVisibility(View.VISIBLE);
            viewHolder.butGoodsDeliver.setVisibility(View.GONE);

            viewHolder.butGoodsClose.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Utils.showToast(mContext, "您点击了关闭");
                }
            });

            viewHolder.butGoodsPay.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    isRefresh = true;
                    //					Utils.showToast(mContext, "您点击了付款");
                    Intent intent = new Intent(mContext, OrderPayActivity.class);
                    //支付总金额 需要传递过去
                    //				//支付总金额 需要传递过去
                    intent.putExtra(DefaultConsts.ORDER_DETAIL_ORDER_SERIAL, orderDetailInfo.getOrderSerial());
                    intent.putExtra(DefaultConsts.ORDER_DETAIL_ORDER_PAY_MONEY, orderDetailInfo.getActualMoney());
                    intent.putExtra(DefaultConsts.ORDER_DETAIL_ORDER_ORDER_TITLE, orderDetailInfo.getGoodsList().get(0).getTitle());
                    intent.putExtra(DefaultConsts.ORDER_DETAIL_ORDER_ORDER_INTRO, orderDetailInfo.getGoodsList().get(0).getTitle());
                    mContext.startActivity(intent);
                }
            });

            SubOrderAdapter subOrderAdapter = new SubOrderAdapter(orderDetailInfo);

            viewHolder.lvOrderView.setAdapter(subOrderAdapter);
            subOrderAdapter.notifyDataSetChanged();

            viewHolder.lvOrderView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    OrderDetailInfo Info = orderDetailInfo;
                    Intent intent = new Intent(mContext, OrderDetailActivity.class);
                    intent.putExtra(DefaultConsts.ORDER_DETAIL_FROM_TYPE, DefaultConsts.ORDER_DETAIL_STATE_ALL);
                    intent.putExtra(DefaultConsts.ORDER_DETAIL_ORDER_ID, Info.getOrderId());
                    mContext.startActivity(intent);

                }
            });
            return convertView;
        }

    }

    class ViewHolder {
        private TextView tvOrderNumber, tvOrderState;
        private MyListView lvOrderView;
        private TextView tvGoodsTotalPrice;
        private Button butGoodsDeliver;
        private Button butGoodsComment;
        private Button butGoodsClose;
        private Button butGoodsPay;
    }

    /*******************
     * 单个订单的详情
     **************************************/

    private class SubOrderAdapter
            extends
            BaseAdapter {

        private OrderDetailInfo orderInfo;

        /**
         *
         */
        public SubOrderAdapter(OrderDetailInfo info) {
            this.orderInfo = info;
        }

        @Override
        public int getCount() {
            //			return 3;
            return (orderInfo == null || orderInfo.getGoodsList().size() == 0) ? 0 : orderInfo.getGoodsList().size();
        }

        @Override
        public Object getItem(int position) {

            return (orderInfo.getGoodsList() == null || orderInfo.getGoodsList().size() == 0) ? null : orderInfo.getGoodsList().get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            SubOrderViewHolder holder;
            if (convertView == null) {
                holder = new SubOrderViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.goods_detail_item, null);
                holder.ivGoodsCover = (ImageView) convertView.findViewById(R.id.goods_detail_item_image);
                holder.tvGoodsIntro = (TextView) convertView.findViewById(R.id.goods_detail_item_name_tv);
                holder.tvGoodsPrice = (TextView) convertView.findViewById(R.id.goods_detail_item_original_price_tv);
                holder.tvGoodsCount = (TextView) convertView.findViewById(R.id.goods_detail_item_original_count_tv);
                holder.tvGoodsSort = (TextView) convertView.findViewById(R.id.goods_detail_item_classify_tv);

                convertView.setTag(holder);
            } else {
                holder = (SubOrderViewHolder) convertView.getTag();
            }

            OrderDetailColum orderDetailColum = (OrderDetailColum) getItem(position);
            if (Utils.isEmpty(orderDetailColum.getCoverUrl())) {//设置默认图片
                holder.ivGoodsCover.setImageResource(R.drawable.atlas_default_img);
            } else {
//				holder.ivGoodsCover.setImageUrl(orderDetailColum.getCoverUrl());
                PicassoUtil.load(mContext, orderDetailColum.getCoverUrl(), R.drawable.atlas_default_img, holder.ivGoodsCover);
            }
            holder.tvGoodsIntro.setText(orderDetailColum.getTitle());
            holder.tvGoodsPrice.setText(" ¥" + Utils.getMoneyFormat(MoneyUtil.divide(orderDetailColum.getSalePrice(), 100)));
            holder.tvGoodsCount.setText("x " + String.valueOf(orderDetailColum.getBuyNum()));
            //获取SUK
            //			Map map = new HashMap();
            //			map.putAll(orderDetailColum.getSkuProp());
            //
            //			Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
            //			String str = null, str1 = null, str2 = null;
            //			while (it.hasNext())
            //			{
            //				Map.Entry<String, String> entry = it.next();
            //				str1 = entry.getKey();
            //				str2 = entry.getValue();
            //				str = str + str1 + ":" + str2 + ",";
            //			}
            //			str = str.substring(4, (str.length() - 1)); //去掉最前面的null 和最后的“，”
            //			holder.tvGoodsSort.setText(str);
            StringBuilder str = new StringBuilder();
            if (orderDetailColum.getSkuProp() != null && orderDetailColum.getSkuProp().size() > 0) {
                for (Entry<String, String> entry : orderDetailColum.getSkuProp().entrySet()) {
                    if (str.length() > 0) {
                        str.append(",");
                    }
                    str.append(entry.getKey() + ": ");
                    str.append(entry.getValue());
                }
            }
            holder.tvGoodsSort.setText(str.toString());

            return convertView;
        }
    }

    private class SubOrderViewHolder {
        private TextView tvGoodsIntro;
        private TextView tvGoodsPrice;
        private TextView tvGoodsCount;
        private TextView tvGoodsSort;
        private ImageView ivGoodsCover;
    }

    @Override
    public void refreshView() {
        if (isRefresh) {
            lastOrderCreatTime = 0L;
            getData(0);
        }
    }

}
